package com.lwq.imserver.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lwq.imserver.exception.AuthenticationException;
import com.lwq.imserver.model.system.SysUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/20 15:37
 */
public class TokenUtil {

    //密钥
    public static final String SECRET = "sdjhakdhajdklsl;o653632";

    public static String createToken(SysUser user, int expire) throws Exception {
//        Calendar nowTime = Calendar.getInstance();
//        nowTime.add(Calendar.HOUR, expire);
//        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim("userId", user.getId().toString())
                .withClaim("userName", user.getName())
                .withClaim("name",user.getUserName())
                .withIssuedAt(new Date())
//                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }


    /**
     * 验证Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token)throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(cutTokenBearer(token));
        }catch (Exception e){
            e.printStackTrace();
            throw new AuthenticationException("凭证已过期，请重新登录");
        }
        return jwt.getClaims();
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Map<String, Claim> parseToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaims();
    }

    public static String cutTokenBearer(String token){
        if(token.startsWith("Bearer ")){
            return token.substring(token.indexOf(" ")+1, token.length());
        }
        return token;
    }
}
